package com.example.auth.exception;

/**
 * @author: LiYang
 * @create: 2023-07-10 15:54
 * @Description:
 * @Version 1.0
 **/

import com.example.auth.utils.Result;
import org.apache.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.List;

@ControllerAdvice  //AOP
public class GlobalExceptionHandler {

    private static final Logger logger = Logger.getLogger(GlobalExceptionHandler.class);

    // 自定义异常处理LyException
    @ExceptionHandler(LyException.class)
    @ResponseBody
    public Result error(LyException e){
        e.printStackTrace();
        return Result.fail(e.getCode(),e.getMsg(),null);
    }

    /**
     * spring security异常
     * @param e
     * @return
     */
    @ExceptionHandler(AccessDeniedException.class)
    @ResponseBody
    public Result error(AccessDeniedException e) throws AccessDeniedException {
        return Result.fail("没有权限");
    }
    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result throwCustomException(MethodArgumentNotValidException methodArgumentNotValidException){

        var errors = methodArgumentNotValidException.getBindingResult().getAllErrors();
        logger.error(errors.get(0).getDefaultMessage());
        if(errors.size() != 0){
            return Result.fail(errors.get(0).getDefaultMessage());
        }
        return null;
    }

    // 全局异常处理
    @ExceptionHandler
    @ResponseBody
    public Result error(Exception e){
        e.printStackTrace();
        return Result.fail("出错啦！");
    }

}
